#!/bin/bash

# 定义目标目录
TARGET_DIR="/usr/local/bin/service"

# 参数处理函数
handle_list() {
  # 列出所有.sh文件
  echo "在 $TARGET_DIR 中找到的脚本文件："
  ls -l "$TARGET_DIR"/*.sh 2>/dev/null | awk 'BEGIN {count=0} {print ++count ") " $9} END {if(count==0) print "未找到 .sh 文件"}'
}

handle_delete() {
  local name=$1
  local service_file="/etc/systemd/system/${name}.service"
  local link_file="/etc/systemd/system/multi-user.target.wants/${name}.service"
  local script_file="${TARGET_DIR}/${name}.sh"

  # 停止服务
  if systemctl is-active --quiet "$name"; then
    echo "正在停止服务 $name..."
    systemctl stop "$name"
  fi

  # 删除文件
  echo "正在删除相关文件："
  [ -f "$script_file" ] && rm -v "$script_file"
  [ -L "$link_file" ] && unlink -v "$link_file"
  [ -f "$service_file" ] && rm -v "$service_file"

  # 重新加载systemd
  systemctl daemon-reload
  echo "服务 $name 已完全删除"
}

# 主逻辑
case "$1" in
  -l|--list)
    handle_list
    ;;
  -d|--delete)
    if [ -z "$2" ]; then
      echo "错误：需要提供要删除的服务名称"
      exit 1
    fi
    handle_delete "$2"
    ;;
  *)
    echo "用法："
    echo "  $0 --list/-l             # 列出所有服务脚本"
    echo "  $0 --delete/-d <name>    # 删除指定服务"
    exit 1
    ;;
esac